package lab2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ArrayThread extends Thread {

    static int length = 60;
    static ReentrantLock lock = new ReentrantLock(false);
    static Condition condition = lock.newCondition();

    private static int arr[][] = new int[3][length];
    int col = 0;
    int row;
    ConsoleProgressBar bar;

    public ArrayThread(int row){
        this.row = row;
        bar = new ConsoleProgressBar("#" + row );
    }

    @Override
    public void run() {
        while (col < length) {
            try {
                lock.lock();
                while (selfFilled() && !allFilled()) {
                    condition.await();
                }
                arr[row][col++] = 1;
                //this.printProgress();
                sleep(100);
                condition.signalAll();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }

    public boolean allFilled() {
        return arr[0][col-1] == 1 && arr[1][col-1] == 1 && arr[2][col-1] == 1;
    }

    public void printProgress(){
//        System.out.println(row+"row progress:");
        bar.update(col, length);
//        System.out.println(row + "," + col);
//        System.out.println();
    }

    public String getProgressStr(){
        return bar.getUpdateStr(col, length);
    }

    public boolean isFinished(){
        return col == length;
    }

    public static void setArr(){
        for (int i = 0; i < 3; ++i){
            for (int j = 0; j < length; ++j){
                arr[i][j] = -1;
            }
        }
    }

    public static void printArr(){
        System.out.println();
        for (int i = 0; i < 3; ++i){
            for (int j = 0; j < length; ++j){
                System.out.print(arr[i][j]);
            }
            System.out.println();
        }
    }

    public boolean selfFilled(){
        return col % 10 == 0 && col != 0;
    }


}
